<template>
  <div class="form">
    <header>注册页面</header>
    <van-form @submit="onSubmit" class="auth-form">
      <van-field
        autocomplete="off"
        v-model="username"
        name="username"
        label="用户名:"
        placeholder="请输入用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^[0-9A-Za-z]{1,10}$/,
            message: '用户名由1-10个数字字母组成',
          },
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码:"
        placeholder="请输入密码"
        :rules="[{ required: true, pattern, message: getpsdMessage }]"
      />
      <van-field
        v-model="repassword"
        type="password"
        name="repassword"
        label="确认密码:"
        placeholder="请再次输入密码"
        :rules="[{ required: true, validator, message: getRepsdMessage }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
      <router-link class="link" replace to="/login"
        >已有账号，直接登录&gt;&gt;
      </router-link>
    </van-form>
  </div>
</template>

<script>
import { Toast } from "vant";
import { registerApi } from "@/api/auth";
export default {
  data() {
    return {
      username: "wangwu",
      password: "123qwe",
      repassword: "123qwe",
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).{6,12}$/,
    };
  },
  methods: {
    // 获取密码输入框输入出错的提醒文字
    getpsdMessage(value, rule) {
      if (value) {
        return "至少包含字母、数字，6-12位";
      } else {
        return "请填写密码";
      }
    },
    // 获取确认密码输入框输入出错的提醒文字
    getRepsdMessage(value, rule) {
      return value ? "两次密码需要一致" : "请再次填写密码";
    },
    // 验证再次输入密码的方法
    validator(value) {
      return value === this.password;
    },
    // 提交
    async onSubmit(...rest) {
      try {
        const res = await registerApi({
          user_name: this.username,
          password: this.password,
        });
        if (res.error) {
          Toast(res.error.response.data.message);
          return;
        }
        Toast("注册成功");
        this.$router.replace("/login");
      } catch (error) {
        Toast(error.response.data.message);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.form {
  background-image: url(../assets/img/bg.png);
  background-size: 100%;
}
header {
  font-weight: 700;
  font-size: 30px;
  text-align: center;
  line-height: 100px;
}
.van-form {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px #e2a94d;
  border: 1px solid #ccc;
  width: 300px;
  // height: 270px;
  padding-top: 30px;
  position: absolute;
  top: 100px;
  left: calc(50% - 150px);
  text-align: center;
  .van-cell {
    height: 60px;
  }
  .btn {
    width: 200px;
    margin: 20px auto;
  }
  .link {
    font-size: 14px;
    line-height: 30px;
    color: #d9a34b;
  }
}
</style>
